package com.weavernorth.humanresource;

import com.weavernorth.retailExperienceAward.utils.convertDateUtil;
import com.weavernorth.util.dateUtils;
import weaver.conn.RecordSet;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;

import java.util.Calendar;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import sun.misc.BASE64Encoder;
import weaver.general.BaseBean;
import weaver.general.Util;

import java.io.IOException;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.Iterator;


//电商绩效接口
public class HRDsjxAction implements Action {

    public static Log log = LogFactory.getLog(HRDsjxAction.class.getName());

    @Override
    public String execute(RequestInfo requestInfo) {
        BaseBean bb = new BaseBean();
        boolean bolFlag=true;
        //主表数据库
        RecordSet rs = new RecordSet();
        SalarRangeUtil salarRangeUtil = new SalarRangeUtil();

        boolean isSuccess = false;
        //获取当前日期
        Calendar now = Calendar.getInstance();
        int day = now.get(Calendar.DAY_OF_MONTH);
        String requestid = requestInfo.getRequestid();//请求ID
        String workflowid = requestInfo.getWorkflowid();//流程ID
        String tablename = requestInfo.getRequestManager().getBillTableName();//表单名称
        bb.writeLog("人事-电商绩效tablename的值是:" + tablename + "\n requestid" + requestid);


        //主表数据库字段
        String tbrq = "";//填表日期
        String yggh = "";//员工工号
        double zfs = 0.0;//总分数
        double jjje = 0.0;//奖金金额


        RecordSet mbrs = new RecordSet();//码表rs
        String mbsql = "";  //查询码表sql

        //1.获取主表单数据
        String sql = " select * from " + tablename + " where requestid =" + requestid;
        bb.writeLog("人事-电商绩效接口sql的值是:" + sql + "\n");
        rs.execute(sql);

        if (rs.next()) {

            //tbrq = rs.getString("tbrq");//填表日期
            Integer strnf=Integer.parseInt(Util.null2String(rs.getString("nf")));
            int strjd = Integer.parseInt(Util.null2String(rs.getString("jd")));//季度
            log.info("季度："+strjd);
            tbrq = dateUtils.LastDayOfMonth(strnf, dateUtils.getMonthByjd(strjd));
            log.info("填报日期："+tbrq);
            yggh = rs.getString("yggh");//员工工号
            zfs = rs.getDouble("zfs");//总分数
            jjje = rs.getDouble("jjje");//奖金金额
            //姓名id
            String strXm=Util.null2String(rs.getString("xm"));
            //zm 增加,判断工资范围是否锁定 开始
            String strGzfw=salarRangeUtil.getGzfwFromUser(strXm);

            String strLockMess = salarRangeUtil.judgeLock(strGzfw, tbrq);
            log.info("工资核算范围返回信息:" + strLockMess);
            if (!"".equals(strLockMess)) {
                strLockMess="工号为:"+yggh+","+strLockMess+"薪资核算结束后，工资范围解除锁定，流程可以继续提交";
                requestInfo.getRequestManager().setMessagecontent(strLockMess);
                return FAILURE_AND_CONTINUE;

            }
            //zm 增加,判断工资范围是否锁定 结束

            //bb.writeLog("人事-电商绩效:日期sxrq的值是:" + tbrq +"\n");


        }


        //2.封装sap请求xml
        StringBuffer xml = new StringBuffer("");


        xml.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:sap-com:document:sap:rfc:functions\">");
//        xml.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:sap-com:document:sap:soap:functions:mc-style\">");

        xml.append("<soapenv:Header/>");
        xml.append("<soapenv:Body>");
        xml.append("<urn:ZHRI_078>");
//        xml.append("<urn:Zhri078>");


        //Return字段
        xml.append("<RETURN>");
//        xml.append("<Return>");

        xml.append("<item>");


        xml.append("<TYPE></TYPE>");
//        xml.append("<Type></Type>");


        xml.append("<ID></ID>");
//        xml.append("<Id></Id>");

        xml.append("<NUMBER></NUMBER>");
//        xml.append("<Number></Number>");

        xml.append("<MESSAGE></MESSAGE>");
//        xml.append("<Message></Message>");

        xml.append("<LOG_NO></LOG_NO>");
//        xml.append("<LogNo></LogNo>");


//        xml.append("<LogMsgNo></LogMsgNo>");
        xml.append("<LOG_MSG_NO></LOG_MSG_NO>");
//        xml.append("<MessageV1></MessageV1>");


        xml.append("<MESSAGE_V1></MESSAGE_V1>");
//        xml.append("<MessageV1></MessageV1>");
        xml.append("<MESSAGE_V2></MESSAGE_V2>");
//        xml.append("<MessageV2></MessageV2>");
        xml.append("<MESSAGE_V3></MESSAGE_V3>");
//        xml.append("<MessageV3></MessageV3>");
        xml.append("<MESSAGE_V4></MESSAGE_V4>");
//        xml.append("<MessageV4></MessageV4>");


        xml.append("<PARAMETER></PARAMETER>");
//        xml.append("<Parameter></Parameter>");

        xml.append("<ROW></ROW>");
       // xml.append("<Row></Row>");

        xml.append("<FIELD></FIELD>");
//        xml.append("<Field></Field>");

        xml.append("<SYSTEM></SYSTEM>");
//        xml.append("<System></System>");

        xml.append("</item>");
        xml.append("</RETURN>");
//        xml.append("</Return>");

        xml.append("<T_9136>");


        //主表数据

        xml.append("<item>");
        xml.append("<PERNR>" + yggh + "</PERNR>");//员工编号(主表)
//        xml.append("<Pernr>"+yggh+"</Pernr>");//员工编号(主表)


        xml.append("<ZJXPF>" + zfs + "</ZJXPF>");//总得分(主表)
//        xml.append("<Zjxpf>"+zfs+"</Zjxpf>");//总得分(主表)


        xml.append("<ZJX_DATE>" + tbrq + "</ZJX_DATE>");//填表日期(主表)
//        xml.append("<ZjxDate>"+tbrq+"<ZjxDate>");//填表日期(主表)

        xml.append("<ZJE>" + jjje + "</ZJE>");//奖金金额(主表)
//        xml.append("<Zje>"+jjje+"<Zje>");//奖金金额(主表)
        xml.append("<ZTYPE>10</ZTYPE>");

        xml.append("</item>");


        xml.append("</T_9136>");

        xml.append("</urn:ZHRI_078>");
//        xml.append("</urn:Zhri078>");

        xml.append("</soapenv:Body>");
        xml.append("</soapenv:Envelope>");


        bb.writeLog("人事-电商绩效接口XML的值是:" + xml.toString());


        //CommonToSapUtil commonToSapUtil=new CommonToSapUtil();
        try {
            //3.推送数据


            String txurl = Util.null2String(bb.getPropValue("personnel-erdos", "dsjxurl"));



            String responseXml = salarRangeUtil.sendPost(txurl, xml.toString(), "utf-8");

            bb.writeLog("人事-电商绩效接SAP返回的值是:" + responseXml.toString());

            //===========SAP 返回解析====================

            String strWorkcode = "";

            //xmlStr为上图格式的字符串


            String EPernr = "";//员工编码
            String testType="";
            String strMessage="";
            int intType = 0;
            Document doc = null;
            try {
                doc = DocumentHelper.parseText(responseXml.toString());
                Iterator<Element> its2 = doc.selectNodes("//TYPE").iterator();
                while (its2.hasNext()) {
                    Element element = its2.next();
                     testType = element.getText();
                    if ("E".equals(testType)) {
                        bolFlag=false;
                        break;
                    }
                    intType++;


                }


                int intMess = 0;

                //返回值失败时,则提示失败
                if ("E".equals(testType)) {
                    Iterator<Element> its3 = doc.selectNodes("//MESSAGE").iterator();
                    while (its3.hasNext()) {
                        Element element2 = its3.next();
                        strMessage = element2.getText();
                        log.info("intMess:" + intMess + ",intType:" + intType);
                        if (intMess == intType) {
                            if (!"".equals(strMessage)) {
                                break;
                            }
                        }

                        intMess++;
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }


            if (bolFlag) {
                return SUCCESS;
            } else {
                if (!"".equals(strMessage)) {
                    requestInfo.getRequestManager().setMessagecontent(strMessage);
                }
                return FAILURE_AND_CONTINUE;
            }


            //4.将员工编号需要更新表单字段
//            String sqlIp="update "+tablename+" set hth="+strWorkcode+" where requestid="+requestid;
//            rs.executeQuery(sqlIp);


            //****************更新员工编号*************************
            //RecordSet updaters = new RecordSet();

//            String updatesql = "update "+tablename+" set hth="+EPernr+" where requestid="+requestid;
//            rs.executeQuery(updatesql);


//            bb.writeLog("update员工号 sql的值:" + updatesql +"\n");
//            bb.writeLog("EPernr员工号 的值:" + EPernr +"\n");

            //******************************************


        } catch (Exception e) {
            e.printStackTrace();
            return FAILURE_AND_CONTINUE;
        }


        //return FAILURE_AND_CONTINUE;

    }
}











